package edu.nwpu.zya.coreops.modules.mail.service.impl;

import edu.nwpu.zya.coreops.modules.mail.entity.MailEntity;
import edu.nwpu.zya.coreops.modules.mail.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import java.util.Date;
import java.util.Objects;

@Service
public class MailServiceImpl implements MailService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Value("${spring.mail.properties.from}")
    private String from;

    @Override
    public void sendMail(MailEntity mailEntity) {
        try {
            //true 表示支持复杂类型数据
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(),true);
            mailEntity.setFrom(from);  //从配置项中获取邮件发送人
            messageHelper.setFrom(mailEntity.getFrom());
            messageHelper.setTo(mailEntity.getTo().split(",")); //按照, 逗号进行分隔
            messageHelper.setSubject(mailEntity.getSubject());
            messageHelper.setText(mailEntity.getText());
            //抄送
            if(!StringUtils.isEmpty(mailEntity.getCc())){
                messageHelper.setCc(mailEntity.getCc());
            }
            //密送
            if(!StringUtils.isEmpty(mailEntity.getBcc())){
                messageHelper.setBcc(mailEntity.getBcc().split(",")); //密抄
            }
            //添加邮件附件
            if(mailEntity.getMultipartFiles()!=null){
                for(MultipartFile multipartFile:mailEntity.getMultipartFiles()){
                    messageHelper.addAttachment(Objects.requireNonNull(multipartFile.getOriginalFilename()),multipartFile);
                }
            }
            // 发送时间
            if(mailEntity.getSentDate()==null){
                mailEntity.setSentDate(new Date());
                messageHelper.setSentDate(mailEntity.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage()); // 正式发送邮件
            mailEntity.setStatus("ok");
            // 打日志
            logger.debug("发送邮件成功：{}->{}",mailEntity.getFrom(),mailEntity.getTo());

        } catch (MessagingException e) {
            logger.error("发送邮件失败：{}->{}",mailEntity.getFrom(),mailEntity.getTo());
            e.printStackTrace();
        }

    }
}
